package com.anfeng.cms.controller;

import com.anfeng.cms.domain.manager.AfManagerInfo;
import com.anfeng.cms.request.manager.LoginReq;
import com.anfeng.cms.request.manager.ManagerUser;
import com.anfeng.cms.service.manager.IAfManagerInfoService;
import com.anfeng.cms.util.CryptoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用户登录登出
 * @author 吴朋
 * @date 2019/7/15
 */
@Controller
@Slf4j
public class LoginController {

    @Autowired
    private IAfManagerInfoService managerInfoService;
    @Autowired
    private HttpServletRequest servletRequest;

    @GetMapping(value = "/login")
    public String loginPage() {
        return "login";
    }

    @PostMapping(value = "/login")
    public void login(LoginReq req, HttpServletResponse response) {
        try {
        // 查询管理员信息
        AfManagerInfo managerInfo = managerInfoService.getManagerInfoByMobile(req.getMobile());
        if (null == managerInfo) {
            response.sendRedirect("/index");
            //return "login";
            return;
        }
        String password = managerInfo.getPassword();
        String shaPassword = CryptoUtil.sha256(req.getPassword());
        if (!password.equals(shaPassword)) {
            response.sendRedirect("/index");
            return;
        }
        ManagerUser loginUser = new ManagerUser();
        BeanUtils.copyProperties(managerInfo, loginUser);
        // 认证成功
        // 将管理员信息放入session中
        HttpSession session = servletRequest.getSession();
        session.setAttribute("loginUser", loginUser);
        // session最大保存一周
        session.setMaxInactiveInterval(7 * 24 * 3600);
            response.sendRedirect("/index");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping(value = "/outlogin")
    public String loginOut() {
        HttpSession session = servletRequest.getSession();
        session.invalidate();
        return "login";
    }

    @GetMapping(value = "/index")
    public String index() {
        return "index";
    }

    @GetMapping(value = "/welcome")
    public String welcome() {
        return "welcome";
    }

}
